package com.lsfb.duishangbaos.HomePage;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lsfb.duishangbaos.Code.CodeMoneyActivity;
import com.lsfb.duishangbaos.Comment.CommentActivity;
import com.lsfb.duishangbaos.HomePage.Setting.SettingActivity;
import com.lsfb.duishangbaos.Order.OrderManageActivity;
import com.lsfb.duishangbaos.R;
import com.lsfb.duishangbaos.Revenue.MyRevenueActivity;
import com.lsfb.duishangbaos.ShopManage.ShopManageActivity;
import com.lsfb.duishangbaos.Utils.Permission;
import com.lsfb.duishangbaos.Utils.StarBar;
import com.lsfb.duishangbaos.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.LsfbAppManager;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.view.Camera.LsfbCamera;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 首页
 * Created by Administrator on 2017/5/9 0009.
 */
@ContentView(R.layout.aty_homepage)
public class HomePageActivity extends LsfbActivity {

    @ViewInject(R.id.aty_homepage_text_name)
    private TextView text_name;

    @ViewInject(R.id.aty_homepage_img_head)
    private SimpleDraweeView img_head;

    @ViewInject(R.id.aty_fenshu)
    private TextView aty_fenshu;

    @ViewInject(R.id.starbar)
    private StarBar starbar;

    private String cash = "";


    /**
     * 封装好的照相机
     */
    private LsfbCamera camera;

    /**
     * 头像存储
     */
    private String mimage = "";

    /**
     * 头像上传回调所用常量
     */
    private static final int REQUEST_CODE_WRITE_SETTINGS = 2;
    private static final int RESULT_OK = -1;
    /**
     * 6.0权限类声明
     */
    private Permission permission;

    /**
     * uir存储
     */
    private Uri muri;

    @Override
    public void initView() {
        //改变系统状态栏颜色
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ViewGroup decorViewGroup = (ViewGroup) window.getDecorView();
        View statusBarView = new View(window.getContext());
        int statusBarHeight = getStatusBarHeight(window.getContext());
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, statusBarHeight);
        params.gravity = Gravity.TOP;
        statusBarView.setLayoutParams(params);
        statusBarView.setBackgroundColor(getResources().getColor(R.color.color_forgive));
        decorViewGroup.addView(statusBarView);

        starbar.setIntegerMark(false);
        starbar.setCanTouch(false);

        permission = new Permission(this);
        //相机权限
        permission.GetCAMEARPermission();
        camera = new LsfbCamera() {
            @Override
            public void resultUri(Uri uri) {
                muri = uri;
            }
        };
    }

    /**
     * 计算系统状态栏高度
     *
     * @param context
     * @return
     */
    private int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = res.getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_homepage_img_head, R.id.aty_homepage_setting, R.id.aty_homepage_btn_dianpu, R.id.aty_homepage_btn_money, R.id.aty_homepage_btn_jinying, R.id.aty_homepage_btn_pinlun,R.id.aty_setting})
    public void onClick(View view) {
        switch (view.getId()) {
            //设置
            case R.id.aty_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            //资料管理
            case R.id.aty_homepage_setting:
                startActivity(new Intent(this, ShopManageActivity.class));
                break;
            //修改头像
            case R.id.aty_homepage_img_head:
                //更改头像
                camera.show(this, this);
                break;
            //订单管理
            case R.id.aty_homepage_btn_dianpu:
                startActivity(new Intent(this, OrderManageActivity.class));
                break;
            //我的营收
            case R.id.aty_homepage_btn_money:
//                startActivity(new Intent(this, MoneyManageActivity.class).putExtra("cash", cash));
                startActivity(new Intent(this,MyRevenueActivity.class));
                break;
            //当面付款
            case R.id.aty_homepage_btn_jinying:
//                startActivity(new Intent(this, OperateActivity.class));
                startActivity(new Intent(this, CodeMoneyActivity.class));
                break;
            //用户评论
            case R.id.aty_homepage_btn_pinlun:
                startActivity(new Intent(this, CommentActivity.class));
                break;
        }
    }

    @Override
    public void initData() {
        getData();
    }

    /**
     * 获取商家信息
     */
    public void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        new BaseInternet().getData_Get(URLString.INFO, hashMap, InfoBean.class, new InfoEvent<InfoBean>(), true, false);
    }

    @EventAnnotation
    public void InfoEvent(InfoEvent<InfoBean> event) {
        switch (event.getCode()) {
            case 200:
                text_name.setText(event.getData().getName());
                if (!event.getData().getImg().isEmpty()) {
                    img_head.setImageURI(Uri.parse(URLString.IMAGES + event.getData().getImg()));
                } else {
                    img_head.setBackgroundResource(R.mipmap.img_head);
                }
                if (event.getData().getScore().isEmpty()) {
                    starbar.setStarMark(0);
                    aty_fenshu.setText("0");
                } else {
                    starbar.setStarMark(Float.valueOf(event.getData().getScore()));
                    aty_fenshu.setText(event.getData().getScore());
                }
                cash = event.getData().getCash();
                break;
            default:
                SN.SnackShow(text_name, event.getMsg());
                break;
        }
    }


    /**
     * 头像选择回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        LsfbLog.e("requestCode" + requestCode);
        LsfbLog.e("resultCode" + resultCode);

        if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Settings.System.canWrite(this)) {
                LsfbLog.e("onActivityResult write settings granted");
            } else {
                LsfbLog.e("请求失败");
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LsfbCamera.REQUESTCODE:
                    LsfbLog.e(muri.toString());
                    camera.crop(muri, 300);
                    break;
                case LsfbCamera.SYSTEMPHOTOS:
                    LsfbLog.e(data.getData().toString());
                    String url = "file://" + LsfbCamera.getPath(this, data.getData());
                    LsfbLog.e("22222222222222" + url);
                    muri = Uri.parse(url);
                    camera.crop(muri, 300);
//                    File zipfile= ZipPic.zippng(mUri.getPath());
//                    camera.crop(Uri.parse("file://"+zipfile.getPath()), 300);
                    break;
                case LsfbCamera.CROPIMG:
                    List<File> list = new ArrayList<>();
                    LsfbLog.e("---------------------------------------------:" + muri.getPath());
                    list.add(new File(muri.getPath()));

                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("img", muri.getPath());
                    // TODO: 2017/4/26 0026 token------
                    new HttpClient().postFile(URLString.UPLOAD, hashMap, list, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            LsfbLog.e(e);
                            LsfbLog.e("上传失败");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            LsfbLog.e("上传success");
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().string());
//                                LsfbLog.e("上传结果" + response.body().string());
                                if (jsonObject.getInt("code") == 200) {
                                    LsfbLog.e("得到回调");
                                    JSONObject img = jsonObject.getJSONObject("data");
                                    mimage = img.getString("img");
                                    upImg();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    break;
            }
        }
    }


    /**
     * 上传头像
     */
    public void upImg() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("img", mimage);
        new BaseInternet().getData(URLString.IMGCHANGE, hashMap, UpImgBean.class, new UpImgEvent<UpImgBean>(), true);
    }

    /**
     * 上传头像的回调
     *
     * @param event
     */
    @EventAnnotation
    public void onEventUpImg(UpImgEvent<UpImgBean> event) {
        switch (event.getCode()) {
            case 200:
                SN.SnackShow(img_head, event.getMsg());
                getData();
                break;
            default:
                SN.SnackShow(img_head, event.getMsg());
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    //点击退出弹出确认提示框
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog();
            return true;
        }
        return true;
    }

    protected void dialog() {

//    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
//    设置Title的图标
        builder.setIcon(R.mipmap.ic_launcher);
//    设置Title的内容
        builder.setTitle("温馨提示");
//    设置Content来显示一个信息
        builder.setMessage("确定要退出应用吗？");
//    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                LsfbAppManager.getAppManager().finishAllActivity();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
//    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
//    显示出该对话框
        builder.show();
    }

}
